package org.example.controller.advice;

import lombok.extern.slf4j.Slf4j;
import org.example.exception.TokenException;
import org.example.exception.UploadException;
import org.example.utils.HttpCode;
import org.example.utils.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.io.IOException;

/**
 * 抛出的异常拦截类
 */
@RestControllerAdvice
@Slf4j
public class ExceptionController {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("捕获到一个异常: {}  , {}",e.getBindingResult().getFieldError().getDefaultMessage(),e.getBindingResult().getAllErrors());
        return Result.fail(502,e.getBindingResult().getFieldError().getDefaultMessage());
    }
    @ExceptionHandler(value = {MultipartException.class})
    public Result methodArgumentNotValidException(MultipartException e){
        log.error("捕获到一个异常: {}  , {}",e.getMessage(),e);
        return Result.fail(HttpCode.UPLOAD_ERROR);
    }
    @ExceptionHandler(value = {TokenException.class})
    public Result TokenException(Throwable e){
        log.error("捕获到一个异常: {} ",e.getMessage());
        return Result.fail(HttpCode.NO_LOGIN);
    }
    @ExceptionHandler(value = {UploadException.class})
    public Result uploadException(Throwable e){
        return Result.fail(5555,e.getMessage());
    }
    @ExceptionHandler(value = {IOException.class})
    public Result ioException(Throwable e){
        log.error("文件异常, {}",e.getMessage());
        return Result.fail(HttpCode.IO_ERROR);
    }


//    @ExceptionHandler(value = {Exception.class})
//    public Result allExceptionHandler(Throwable throwable){
//        log.error("捕获到一个异常: {}  , {}",throwable.getMessage(),throwable);
//        return Result.fail(555,throwable.getMessage());
//    }
}
